import {login} from "../../api/shop";
import Util from '../../utils/util.js';

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    topHeight: 60,
    btnDisable: false,

    username: "",
    password: "",

    showPassword: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;

    this.setData({
      navH: app.globalData.navHeight,
      barHeight: app.globalData.barHeight || 20,
    });
    const accessToken = wx.getStorageSync("shop_accessToken");
    if (!Util.isEmpty(accessToken)) {
      wx.redirectTo({
        url: '/pages/console/index'
      })
    }
  },

  inputName(e) {
    this.setData({
      [e.target.id]: e.detail.value || ""
    })

    if (Util.isEmpty(this.data.username) || Util.isEmpty(this.data.password)) {
      this.setData({
        btnDisable: false
      })
    } else {
      this.setData({
        btnDisable: true
      })
    }

  },

  showPassword(e) {
    this.setData({
      showPassword: !this.data.showPassword
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  shopLogin(e) {
    const that = this,
      username = this.data.username,
      password = this.data.password;

    if (Util.isEmpty(username))
      return Util.Tips({title: '登陆账号必填', hideMask: true});

    if (Util.isEmpty(password))
      return Util.Tips({title: '密码必填', hideMask: true});

    that.setData({
      btnActive: false
    })

    login({username: username, password: password})
      .then(res => {
        wx.setStorageSync("shop_accessToken", res.data.accessToken)
        wx.setStorageSync("SHOP_ADMIN", JSON.stringify(res.data))
        Util.Tips({title: "登陆成功"}, {tab: 5, url: "../console/index"})
      })
      .catch(err => {
        return Util.Tips({title: err, hideMask: true});
      }).finally(() => {
      that.setData({
        btnActive: true
      })
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})